<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2022/6/24
 * Time: 12:30
 */

namespace app\common\lib;


class Aes
{
    //密钥 须是16位
    public $key ;

    public $iv ;

    protected static $instance;

    public function __construct()
    {
        $config = config('param.aes');
        $platform = strtoupper(request()->platform);
        $this->key = $config[$platform]['key'];
        $this->iv = $config[$platform]['iv'];
    }

    public static function getInstance()
    {
        //        if(is_object(self::$instance)){
//            return self::$instance;
//        }


        return new self();
    }

    /**
     * 解密字符串
     * @param string $str 字符串
     * @return string
     */
    public  function decode($str)
    {
        $result = openssl_decrypt(base64_decode($str),"AES-256-CBC",$this->key,OPENSSL_RAW_DATA,$this->iv);
        $data = json_decode($result, true);

        return $data ?? $result;
    }

    /**
     * 加密字符串
     * @param string $data 字符串
     * @return string
     */
    public  function encode($data)
    {
        if(is_object($data)){
            $data = $data->toArray();
            $str = json_encode($data,256);
        }else if(is_array($data)){
            $str = json_encode($data,256);
        }else{
            $str = $data;
        }

        return base64_encode(openssl_encrypt($str,"AES-256-CBC",$this->key,OPENSSL_RAW_DATA,$this->iv));
    }
}